#!/usr/bin/perl
#upgrade-lib.pl
#Library for editing webmin users, password and access rights

do '../web-lib.pl';

&init_config();

#return $err_msg
sub dcrypt_uploadfile()
{
	my ($out, $err_msg);

	$err_msg = "";

	unless(-e $config{'uploadfile'})
	{
		$err_msg = $text{'err_msg_file_noexist'};
		return $err_msg;
	}

	&ez_system('mv', $config{'uploadfile'}, $config{'uploadfilecpt'});
	$out = &ez_system12('/sbin/ccrypt', '-d', '-K', $config{'key'}, $config{'uploadfilecpt'});
	if($out)
	{
		$err_msg = $text{'err_msg_fileformat'};
		return $err_msg;
	}
	return $err_msg;
}

#return $err_msg
sub extract_uploadfile()
{
	my ($out, $err_msg);

	$err_msg = "";

	unless(-e $config{'uploadfile'})
	{
		$err_msg = $text{'err_msg_fileformat'};
		return $err_msg;
	}

	&ez_system('mv', $config{'uploadfile'}, $config{'uploadfiletar'});
	$out = &ez_system('tar', 'xvf', $config{'uploadfiletar'}, "-C", $config{'tmpdir'});

	&ez_system('rm', '-f', $config{'uploadfiletar'});
	
	if($out)
	{
		$err_msg = $text{'err_msg_fileformat'};
		return $err_msg;
	}
	return $err_msg;
}

sub get_current_version()
{
	my (@version, $i);
	
	open(VERSION, $config{'versionfile'});
	@version = <VERSION>;
	close(VERSION);

	for($i = 0; $i < @version; $i++)
	{
		chomp($version[$i]);
		$version[$i] =~ s/#.*$//;
		if($version[$i] =~ /^VERSION\s*=/)
		{
			$version[$i] =~ s/^VERSION\s*=\s*//;
			return $version[$i];
		}
	}

	return "";
}

sub get_sysvol_mount_dev()
{
	my (@mlist, $i, @line);

	@mlist = `mount`;

	for($i = 0; $i < @mlist; $i++)
	{
		$mlist[$i] =~ s/#.*$//;
		chomp($mlist[$i]);
		
		@line = split(/\s+/, $mlist[$i]);
		if($line[2] eq '/sysvol')
		{
			return $line[0];
		}
	}

	return "";
}

#this function for mdm module remote call
#mdm_update(void)
sub mdm_update()
{
        my ($err_msg, $out, $err_no, $log_ev, $log_msg, $log_lev, $sv_mount_dev);

	$sv_mount_dev = &get_sysvol_mount_dev();

	$err_msg = &dcrypt_uploadfile();
	if($err_msg)
	{	
	    return $err_msg;
	}

	$err_msg = &extract_uploadfile();
	if($err_msg)
	{
	    return $err_msg;
	}

	&ez_system("cp", "-f", $config{'upgradepl'}, $config{'upgradeplcpt'});

	if(-e $config{'sbinupgradepl'})
	{
	    &ez_system("rm", "-f", $config{'sbinupgradepl'});
	}

	$out = ez_system12("/sbin/ccrypt", "-d", "-K", $config{"key"}, $config{'upgradeplcpt'});
	if($out)
	{
	    $err_msg = $text{'err_msg_fileformat'};
	}

	$err_no = &ez_system("/sbin/upgrade.pl");

	$err_no = $err_no / 256;
	if($err_no)
	{
	    if($err_no == $text{'err_no_oldversion'})
	    {
		$err_msg = $text{'err_msg_oldversion'};
		return $err_msg;
	    }

	    if($err_no == $text{'err_no_erroemid'})
	    {
		$err_msg = $text{'err_msg_oemid'};
		return $err_msg;
	    }

	    if($err_no == $text{'err_no_mountdir'})
	    {
		$err_msg = $text{'err_msg_mountdir'};
		return $err_msg;
	    }

	    if($err_no == $text{'err_no_tmppak'})
	    {
		$err_msg = $text{'err_msg_fileformat'};
		return $err_msg;
	    }
	}

	return "Success";
}

1;
